import flvjs from "flv.js";
import { isRef } from "vue";

const useFlv = ({ videoId, cameraUrl }) => {
  let flvPlayer = null;
  let lastDecodedFrame = 0;
  let isClick = false;
  const { VITE_API_URL } = import.meta.env;

  function getFlv() {
    let videoElement = document.getElementById(videoId) as HTMLMediaElement;

    const videoPath = isRef(cameraUrl)
      ? `${VITE_API_URL}/digitaltwins/api/v1/camera/get?rtspUrl=${cameraUrl.value}`
      : `${VITE_API_URL}/digitaltwins/api/v1/camera/get?rtspUrl=${cameraUrl}`;
    // const rstUrl = encodeURI("D:\\download\\0730.mp4");
    // const videoPath = `http://10.1.2.174:8082/api/v1/camera/get?rtspUrl=${rstUrl}`;

    if (!videoElement) {
      setTimeout(() => {
        getFlv();
      }, 1000);
      return;
    }

    if (flvjs.isSupported()) {
      flvPlayer = flvjs.createPlayer(
        {
          type: "flv", // 指定视频类型，特别注意此处伟flv
          isLive: true, // 开启直播
          hasAudio: false, //需要设置为false不然播放不了视频
          cors: true, // 开启跨域访问
          url: videoPath //FLV视频地址
        },
        {
          enableWorker: false, //不启用分离线程
          enableStashBuffer: false, //关闭IO隐藏缓冲区
          reuseRedirectedURL: true, //重用301/302重定向url，用于随后的请求，如查找、重新连接等。
          autoCleanupSourceBuffer: true //自动清除缓存
        }
      );
      flvPlayer.attachMediaElement(videoElement);
      flvPlayer.load();
      flvPlayer.play(); //开始播放
      // flvPlayer.stop(); //停止播放时打开
      flvPlayer.on(flvjs.Events.ERROR, () => {
        flvPlayer && reloadVideo();
      });
      // 监听错误事件，进行重连
      flvPlayer.on(flvjs.Events.ERROR, (errorType, errorDetail, errorInfo) => {
        console.log("errorType:", errorType);
        console.log("errorDetail:", errorDetail);
        console.log("errorInfo:", errorInfo);
        flvPlayer && reloadVideo();
      });

      // 监听统计信息，处理卡顿
      flvPlayer.on("statistics_info", stats => {
        if (lastDecodedFrame === 0) {
          lastDecodedFrame = stats.decodedFrames;
          return;
        }

        if (lastDecodedFrame === stats.decodedFrames && !flvPlayer.paused && !isClick) {
          // 如果decodedFrames没有变化，可能卡住了，重连
          flvPlayer && reloadVideo();
          lastDecodedFrame = 0;
          console.log("卡顿重联", lastDecodedFrame, stats.decodedFrames);
        } else {
          lastDecodedFrame = stats.decodedFrames;
        }
      });
    }
  }
  const reloadVideo = () => {
    destoryVideo();
    getFlv();
  };
  const destoryVideo = () => {
    if (flvPlayer) {
      flvPlayer!.pause();
      flvPlayer!.unload();
      flvPlayer!.detachMediaElement();
      flvPlayer!.destroy();
      flvPlayer = null;
    }
  };
  let timer = null;
  const videoClick = () => {
    isClick = true;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      isClick = false;
    }, 5000);
  };
  return {
    getFlv,
    videoClick,
    destoryVideo,
    reloadVideo
  };
};
export default useFlv;
